<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/6
 * Time: 14:49
 */

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\models\datas\CardBatch;
use common\models\datas\Site;
use doumiaoduo\buildform\BuildForm;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\Response;
use yii\web\BadRequestHttpException;
use common\components\actions\DeleteAction;
use yii\widgets\ActiveForm;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ArtRelation;
use zhtfrontend\models\datas\ArtTeaching;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\ClassroomAttr;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Teacher;
use common\components\helpers\Util;

class ArtteachingController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $param = Json::decode(\Yii::$app->request->post('param'));
            $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
            $data = ArtTeaching::find()->orderBy('id DESC');
            if (!empty($param['searchData'])) {
                $search_data = array_filter($param['searchData']);
                if (!empty($search_data['title'])) {
                    $data->andWhere(['like', 'title', $search_data['title']]);
                }
                if (!empty($search_data['class_day'])) {
                    $data->andWhere(['class_day'=>$search_data['class_day']]);
                }
                if (!empty($search_data['type'])) {
                    $data->andWhere(['type'=>$search_data['type']]);
                }
            }
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
            $ajax_object = new AjaxObject();
            $ajax_object->data = Fun::asArray($model, ['operate']);
            $ajax_object->pages = $pages;
            return $ajax_object;
        }
        return $this->render('index');
    }


    public function actionCreate()
    {
        $model = new ArtTeaching();
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        $teacher = Teacher::find()->where(['is_teaching_art'=>1,'status'=>1])->all();
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $post = \Yii::$app->request->post();
            //art_teaching组装title
            //类型
            $type = '';
            switch ($model->type) {
                case 1:
                    $type = '益智';
                    break;
                case 2:
                    $type = '音乐';
                    break;
                case 3:
                    $type = '形体';
                    break;
            }
//            //节次
//            $lesson = $model->class_count."节";
            //时间
            $class_day = Util::getWeek($model->class_day);
            //时长
            $star_time = str_replace(':','',$model->star_time);
            $end_time = str_replace(':','',$model->end_time);
            $start_second = (int)substr($star_time, 2);
            $end_second = (int)substr($end_time, 2);
            if(strlen($star_time) == 3){
                $start_second = (int)substr($star_time, 1);
            }
            if(strlen($end_time) == 3){
                $end_second = (int)substr($end_time, 1);
            }
            $class_lenght = (floor($end_time / 100) - floor($star_time / 100)) * 60 + ($end_second-$start_second);
            $model->title = $type.'-'.$class_day.'-'.$model->star_time.'-'.$model->end_time;
            if($model->save(false)){
                $arrangement_data = [];
                for($i=0;$i<count($post['teacher']);$i++){
                    if(isset($post['teacher'][$i])){
                        $arrangement_data [$i] = [
                            'teacher' => $post['teacher'][$i],
                            'course' => $post['course'][$i],
                            'classroom' => $post['classroom'][$i],
                        ];
                    }
                }
                foreach ($arrangement_data as $k=>$v){
                    $coures = Course::findOne($v['course']);
                    $arrangement = new Arrangement();
                    $arrangement->course_id = $v['course'];
                    $arrangement->teacher_id = $v['teacher'];
                    $arrangement->classroom_id = $v['classroom'];
                    $arrangement->class_length = $class_lenght;
                    $arrangement->class_count = $model->class_count;
                    $arrangement->max_number = $model->max_count;
                    $arrangement->is_booking = 1;
                    $arrangement->admin_id = \Yii::$app->user->id;
                    $arrangement->is_delete = 0;
                    $arrangement->is_online = 1;
                    $arrangement->teaching_methods = 2;
                    $arrangement->is_group = 0;
                    $arrangement->category_id = $model->type;
                    $arrangement->mechanic_id = $coures->mechince_id;
                    if($arrangement->save(false)){
                        $relation = new ArtRelation();
                        $relation->art_teaching_id = $model->id;
                        $relation->arrangement_id = $arrangement->id;
                        $relation->lesson = $k+1;
                        $relation->save(false);
                    }
                }

                //生成班级
                $classManage = new ClassManage();
                $classManage->class_code = 'c'.time();
                $classManage->associate_id = $model->id;
                $classManage->type = 2;
                $classManage->save(false);
                return $this->redirectMessage('添加成功',Fun::url(['artteaching/index']));
            }
        }
        return $this->render('create',['model'=>$model,'teacher'=>$teacher]);
    }

    public function actionGettype(){
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            //$teacher = Teacher::find()->where(['cate_id'=>\Yii::$app->request->post('type_id'),'is_headmaster'=>0,'status'=>1])->asArray()->all();
            $classroom = Classroom::find()->asArray()->all();
            $course = Course::find()->where(['type_id'=>\Yii::$app->request->post('type_id'),'is_artteaching'=>1,'status'=>1])->asArray()->all();
            $data = [
                //'teacher' => $teacher,
                'classroom' => $classroom,
                'course' => $course,
            ];
            return $data;
        }
    }

    public function actionUpdate()
    {
        $id = \Yii::$app->request->get('id');
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = ArtTeaching::findOne($id);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        $teacher = Teacher::find()->where(['is_teaching_art'=>1,'status'=>1])->all();
        $classroom = Classroom::find()->asArray()->all();
        $course = Course::find()->where(['type_id'=>$model->type,'status'=>1])->asArray()->all();
        //取art_relation
        $relation = ArtRelation::find()->where(['art_teaching_id'=>$id])->all();
        $class = [];
        $arr_id = [];
        foreach ($relation as $k=>$v){
            $arrangement = Arrangement::findOne($v->arrangement_id);
            $class[$v->lesson] = [
                'teacher' => $arrangement->teacher_id,
                'course' => $arrangement->course_id,
                'classroom' => $arrangement->classroom_id,
                'id'=>$arrangement->id,
            ];
            $arr_id[$k] = $arrangement->id;
        }

        //print_r($model->load(\Yii::$app->request->post()));echo "<hr/>";print_r($model->validate());exit;
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $post = \Yii::$app->request->post();
            //art_teaching组装title
            //类型
            $type = '';
            switch ($model->type) {
                case 1:
                    $type = '益智';
                    break;
                case 2:
                    $type = '音乐';
                    break;
                case 3:
                    $type = '形体';
                    break;
            }
            //节次
//            $lesson = $model->class_count."节";
            //时间
            $class_day = Util::getWeek($model->class_day);
            //时长
            $star_time = str_replace(':','',$model->star_time);
            $end_time = str_replace(':','',$model->end_time);
            $start_second = (int)substr($star_time, 2);
            $end_second = (int)substr($end_time, 2);
            if(strlen($star_time) == 3){
                $start_second = (int)substr($star_time, 1);
            }
            if(strlen($end_time) == 3){
                $end_second = (int)substr($end_time, 1);
            }
            $class_lenght = (floor($end_time / 100) - floor($star_time / 100)) * 60 + ($end_second-$start_second);
            $model->title = $type.'-'.$class_day.'-'.$model->star_time.'-'.$model->end_time;
            if ($model->save(false)) {
                Arrangement::deleteAll(['id' =>$arr_id]);
                ArtRelation::deleteAll('art_teaching_id=:id',[':id'=>$id]);
                $arrangement_data = [];
                for($i=0;$i<count($post['teacher']);$i++){
                    if(isset($post['teacher'][$i])){
                        $arrangement_data [$i] = [
                            'teacher' => $post['teacher'][$i],
                            'course' => $post['course'][$i],
                            'classroom' => $post['classroom'][$i],
                        ];
                    }
                }
                foreach ($arrangement_data as $k=>$v){
                    $course = Course::findOne($v['course']);
                    $arrangement = new Arrangement();
                    $arrangement->course_id = $v['course'];
                    $arrangement->teacher_id = $v['teacher'];
                    $arrangement->classroom_id = $v['classroom'];
                    $arrangement->class_length = $class_lenght;
                    $arrangement->class_count = $model->class_count;
                    $arrangement->max_number = $model->max_count;
                    $arrangement->is_booking = 1;
                    $arrangement->admin_id = \Yii::$app->user->id;
                    $arrangement->is_delete = 0;
                    $arrangement->is_online = 1;
                    $arrangement->teaching_methods = 2;
                    $arrangement->is_group = 0;
                    $arrangement->category_id = $model->type;
                    $arrangement->mechanic_id = $course->mechince_id;
                    if($arrangement->save(false)){
                        $relation = new ArtRelation();
                        $relation->art_teaching_id = $model->id;
                        $relation->arrangement_id = $arrangement->id;
                        $relation->lesson = $k+1;
                        $relation->save(false);
                    }
                }
                return $this->redirectMessage('添加成功',Fun::url(['artteaching/index']));
            }
        }
        return $this->render('create', ['model' => $model,'class'=>$class,'teacher'=>$teacher,'course'=>$course,'classroom'=>$classroom]);
    }

    public function actionView(){
        $this->layout='@app/views/layouts/iframe.php';
        $art_id = \Yii::$app->request->get('id');
        $model = ArtTeaching::findOne($art_id);
        $arrangement = (new \yii\db\Query())->select(['ar.*','a.*'])
            ->from('{{%art_relation}} ar')
            ->leftJoin('{{%arrangement}} a','a.id = ar.arrangement_id')
            ->where(['ar.art_teaching_id'=>$art_id])
            ->orderBy('ar.lesson ASC')
            ->all(Fun::getSiteDb());
        $data = [];
        foreach ($arrangement as $item){
            $teacher = Teacher::findOne($item['teacher_id']);
            $coures = Course::findOne($item['course_id']);
            $classroom = Classroom::findOne($item['classroom_id']);
            $row['coures_name'] =isset($coures)?$coures->name:'';
            $row['teacher_name'] =isset($teacher)?$teacher->name:'';
            $row['classroom_name'] =isset($classroom)?$classroom->name:'';
            $row['lesson'] = $item['lesson'];
            $row['class_time'] = Util::getWeek($model->class_day).' '.$model->star_time.'-'.$model->end_time;
            $data[] = $row;
        }
        return $this->render('view',['data'=>$data]);
    }

    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => ArtTeaching::className(),
                'message' => ['success' => \Yii::t('zhtfrontend', '删除成功')],
                'redirectTo' => 'artteaching/index',
            ],
        ];
    }


}